# backend/tts.py
import os
import uuid
import requests
import logging
from typing import Optional

logger = logging.getLogger("tts")

AUDIO_DIR = os.getenv("AUDIO_DIR", "./audio")
INDEX_TTS_API = os.getenv("INDEX_TTS_API", "http://localhost:6006/tts")  # TODO: change to your index-tts
os.makedirs(AUDIO_DIR, exist_ok=True)

def synth_tts_savefile(text: str) -> str:
    """
    Call index-tts and save returned audio bytes to file. Return file path (full).
    """
    try:
        resp = requests.post(INDEX_TTS_API, json={"text": text}, timeout=30)
        if resp.status_code == 200:
            filename = f"{uuid.uuid4().hex}.wav"
            path = os.path.join(AUDIO_DIR, filename)
            with open(path, "wb") as f:
                f.write(resp.content)
            return path
        else:
            logger.error("TTS status: %s", resp.status_code)
            return ""
    except Exception:
        logger.exception("TTS synth failed")
        return ""

def synth_tts_bytes(text: str) -> Optional[bytes]:
    """
    Call index-tts and return audio bytes (no disk write).
    """
    try:
        resp = requests.post(INDEX_TTS_API, json={"text": text}, timeout=30)
        if resp.status_code == 200:
            return resp.content
        else:
            logger.error("TTS status: %s", resp.status_code)
            return None
    except Exception:
        logger.exception("TTS synth failed")
        return None
